import React, { Component } from 'react';
import TheTable from '@/components/TheTable'
import ThePagination from '@/components/ThePagination'
import TheImage from '@/components/TheImage'
import TheArea from '@/components/TheArea'
import TheButton from '@/components/TheButton'
import { Button, DatePicker, Form, Input, Select, Space, Switch } from 'antd';
import { SearchOutlined } from "@ant-design/icons";
import { useRef } from 'react';
import { apiGetStoreInfoPage, apiStoreInfoUpdateStoreState, apiStoreInfoStoreUserInfo, apiStoreInfoUpdatePassword } from '@/request/store'
import { useState } from 'react';
import { getDateTime3 } from '@/utils/getDate'
import _ from 'lodash'
import TheDialog from '@/components/TheDialog'
import '../style/index.less'

const { RangePicker } = DatePicker

const SearchHeader = ({ getSearchValue, goAdd }) => {
  const areaRef = useRef()
  const formRef = useRef()
  const [area, setArea] = useState({})
  const setAreaData = (value) => {
    value = {
      addressProvince: value.provinceName,
      addressCity: value.cityName,
      addressDistrict: value.areaName
    }
    setArea(value)
  }
  const onFinish = values => {
    if (!_.isEmpty(values.time)) {
      values.createdTimeStart = getDateTime3(values.time[0])
      values.createdTimeEnd = getDateTime3(values.time[1])
    }
    delete (values.time)
    values = {
      ...values,
      ...area
    }
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    getSearchValue(values)
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      storeName: '',
      contactsOrMobile: '',
      area: '',
      isProprietary: null,
      time: []
    })
    areaRef.current.init()
    getSearchValue({})
  }
  return <div className='search-box' style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
    <Form ref={formRef} onFinish={onFinish} layout='inline'>
      <Form.Item name={"storeName"}>
        <Input style={{ width: 120 }} suffix={<SearchOutlined />} placeholder={"门店名称"} />
      </Form.Item>
      <Form.Item name={"contactsOrMobile"}>
        <Input style={{ width: 120 }} suffix={<SearchOutlined />} placeholder={"联系方式"} />
      </Form.Item>
      <Form.Item name={"area"}>
        <TheArea ref={areaRef} setAreaData={setAreaData} />
      </Form.Item>
      <Form.Item name={"isProprietary"}>
        <Select placeholder="门店类型"
          style={{ width: 100 }}
          options={[
            {
              value: 'Y',
              label: '自营'
            },
            {
              value: 'N',
              label: '非自营'
            }
          ]} />
      </Form.Item>
      <Form.Item name={"time"} label="入驻时间">
        <RangePicker style={{ width: 240 }} />
      </Form.Item>
      <Form.Item>
        <Space>
          <Button type='primary' htmlType='submit'>搜索</Button>
          <Button onClick={reset}>重置</Button>
        </Space>
      </Form.Item>
    </Form>
    <TheButton onClick={goAdd}>新增门店</TheButton>
  </div>
}

class List extends Component {
  formRef = React.createRef()
  state = {
    columns: [
      {
        title: '门店名称',
        dataIndex: 'storeName',
        key: 'storeName'
      },
      {
        title: '门店图片',
        dataIndex: 'storeShowFile',
        key: 'storeShowFile',
        render: (text, record) => {
          return <TheImage height={80} width={80} src={record.storeShowFile} />
        }
      },
      {
        title: '联系人',
        dataIndex: 'storeContacts',
        key: 'storeContacts'
      },
      {
        title: '联系方式',
        dataIndex: 'userMobile',
        key: 'userMobile'
      },
      {
        title: '地区',
        render: (text, record) => {
          return `${record.addressProvince} ${record.addressCity} ${record.addressDistrict}`
        }
      },
      {
        title: '详细地址',
        dataIndex: 'addressDetail',
        key: 'addressDetail'
      },
      {
        title: '开店/关店',
        dataIndex: 'storeStatus',
        key: 'storeStatus',
        render: (text, record) => {
          return <Switch onChange={() => this.storeStatusChange(record.storeStatus, record.storeId)} checked={record.storeStatus === 'Y'} />
        }
      },
      {
        title: '入驻时间',
        dataIndex: 'createTime',
        key: 'createTime'
      },
      {
        title: '门店类型',
        dataIndex: 'isProprietary',
        key: 'isProprietary',
        render: (text, record) => {
          return record.isProprietary === 'Y' ? '自营' : '非自营'
        }
      },
      {
        title: '操作',
        fixed: 'right',
        render: (text, record) => {
          return <Space>
            <TheButton haspermi={['store:details']} onClick={() => this.props.history.push(`/store/details/${record.storeId}`)}>门店详情</TheButton>
            <TheButton haspermi={['store:information']} onClick={() => this.openDialog(record.storeId)}>账号信息</TheButton>
          </Space>
        }
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10
    },
    total: 0,
    searchValue: {},
    visible: false,
    userInfo: [],
    passwordVisible: false
  }
  async componentDidMount() {
    await this.getData()
  }
  getData = async () => {
    this.setState({ loading: false })
    const { pageData, searchValue } = this.state
    let res = await apiGetStoreInfoPage({ ...pageData, ...searchValue, approvalStatus: 'T' })
    if (res.code === 0 && res.data) {
      this.setState({
        dataSource: res.data,
        loading: false,
        pageData: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        total: res.totalCount
      })
    } else {
      this.setState({
        loading: false
      })
    }
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  }
  getSearchValue = values => {
    this.setState({ searchValue: values }, () => this.getData())
  }
  openDialog = async storeId => {
    let res = await apiStoreInfoStoreUserInfo({ storeId })
    if (res.code === 0) {
      const data = res.data
      let userInfo = [
        {
          title: '联系人',
          value: data.userName
        },
        {
          title: '联系方式',
          value: data.userMobile
        },
        {
          title: '账号',
          value: data.loginName
        },
        {
          title: '密码',
          value: <div>
            ****** <TheButton onClick={() => this.updatePassword(storeId, data.userId)}>修改密码</TheButton>
          </div>
        },
      ]
      this.setState({
        storeId,
        visible: true,
        userInfo
      })
    } else {
      React.$message({
        type: 'info',
        content: '获取详情失败'
      })
    }
  }
  closeDialog = () => {
    this.setState({ storeId: '', visible: false, userInfo: [] })
  }
  updatePassword = (storeId, userId) => {
    this.setState({
      passwordVisible: true,
      userId
    })
  }
  closePasswordDialog = () => {
    this.setState({
      passwordVisible: false
    })
  }
  caonfirmUpdatePassword = async value => {
    React.$confirm({
      title: '您确认更改此账户密码吗？',
      onOk: async () => {
        let res = await apiStoreInfoUpdatePassword({ ...value, userId: this.state.userId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '密码修改成功'
          })
          this.closePasswordDialog()
          this.closeDialog()
          this.getData()
        }
      }
    })
  }
  storeStatusChange = (storeStatus, storeId) => {
    React.$confirm({
      title: `您确认${storeStatus === 'Y' ? '关闭' : '开启'}此店铺吗？`,
      onOk: async () => {
        let res = await apiStoreInfoUpdateStoreState({ state: storeStatus === 'Y' ? 'N' : 'Y', storeId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: `店铺${storeStatus === 'Y' ? '关闭' : '开启'}成功`
          })
          this.getData()
        }
      }
    })
  }
  /**
* @desc 确认自定义密码验证
* @params Reg {rule} 验证规则
* @params string {value} 需要验证的字符串
* @params fun {callback} 回调函数
* */
  validatePassword = (rule, value, callback) => {
    const password = this.formRef.current.getFieldsValue(['password']).password;
    if (value !== password) {
      callback('确认两次输入的密码一致')
    }
    callback()
  }
  render() {
    const { columns, dataSource, pageData: { pageNo, pageSize }, total, loading, visible, userInfo, passwordVisible } = this.state
    return (
      <div className='p-layout-box'>
        <SearchHeader getSearchValue={this.getSearchValue} goAdd={() => this.props.history.push('/store/list/add')} />
        <div className='p-layout-content-pagination'>
          <TheTable scroll={{ x: 'max-content', y: '63vh' }} columns={columns} dataSource={dataSource} loading={loading} />
          <ThePagination pageNo={pageNo} pageSize={pageSize} total={total} pageChange={this.pageChange} />
          <TheDialog
            title="账号信息"
            width={400}
            visible={visible}
            footer={null}
            handleCancel={this.closeDialog}
          >
            <div className='user-dialog'>
              {
                userInfo.map(v => {
                  return <div className='user-item'>
                    <div>{v.title}:</div>
                    <div>{v.value}</div>
                  </div>
                })
              }
              <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Button type='primary' onClick={this.closeDialog}>返回</Button>
              </div>
            </div>
          </TheDialog>
          <TheDialog
            title="修改密码"
            width={400}
            visible={passwordVisible}
            footer={null}
            handleCancel={this.closePasswordDialog}
          >
            <Form ref={this.formRef} onFinish={this.caonfirmUpdatePassword}>
              <Form.Item label="新密码" name={'password'} rules={[{ required: true, message: "请输入密码" }, {
                pattern: /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*()_.]+)$)^[\w~!@#$%^&*()_.]{8,16}$/,
                message: "密码应为字母，数字，特殊符号(~!@#$%^&*()_.)，两种及以上组合，8-16位字符串，如：abcd@1234"
              }]}>
                <React.FormPassword placeholder={'请输入新密码'} />
              </Form.Item>
              <Form.Item label="确认密码" name={'confirmPassword'} rules={[{ required: true, message: "请确认密码" }, { validator: this.validatePassword }]}>
                <React.FormPassword placeholder={'请确认密码'} />
              </Form.Item>
              <Form.Item>
                <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                  <Space>
                    <Button onClick={this.closePasswordDialog}>取消</Button>
                    <Button type='primary' htmlType='submit'>确认</Button>
                  </Space>
                </div>
              </Form.Item>
            </Form>
          </TheDialog>
        </div>
      </div>
    );
  }
}

export default List;
